Crate assert_float_eq

source ·
Expand description

Assertions that two floating point numbers are approximately equal.

Floating-point equality is difficult, and therefore numerous macros are provided. At the most simple, assert_float_absolute_eq and assert_float_relative_eq assert that the difference between two floats is smaller than epsilon (default 1e-6) absolutely or relatively, respectively.

However, due to the decreasing precision of floating-point numbers at large values, and the desire for high-stringency, macros to detect whether a floating point is within a number of “steps” of another are provided. assert_f32_near and assert_f64_near assert whether an f32 or f64 is within n “steps” (default 4) of another, respectively. A floating-point step is an increment to the bit-wise pattern of the float, for example, if a float is represented in-memory as 0x0000FFFF, then the next float would be 0x00010000. This allows float equality comparisons to floating-point numbers at any precision, simplifying equality checks for extremely high or low floats without sacrificing accuracy.

For example, for a 32-bit float of value 3e37, each step is ~4e30, a gargantuan value (but only a small fraction, ~0.00001% of the total value).

In addition to the assert_* macros, which panic if the condition is not true, assert_float_eq also has expect_* macros, which return a Result<(), T: Display>, when panicking is not desirable.

Macros

Assert two 32-bit floats are within n steps of each other.
Assert two 64-bit floats are within n steps of each other.
Assert the absolute error between two values is less than epsilon.
Assert the relative error between two values is less than epsilon.
Expect two 32-bit floats are within n steps of each other.
Expect two 64-bit floats are within n steps of each other.
Expect the absolute error between two values is less than epsilon.
Expect the relative error between two values is less than epsilon.